package com.test08_面向对象应用;

public class YootkDemo_05 {

    public static void main(String[] args) {
        // Array arr = new Array();
        // Array arr = new SortArray();
        Array arr = new ReverseArray();
        System.out.println(arr.add(8));
        System.out.println(arr.add(3));
        System.out.println(arr.add(10));
        System.out.println(arr.add(5));
        System.out.println(arr.add(20));
        arr.increment(3);
        System.out.println(arr.add(30));
        System.out.println(arr.add(80));
        System.out.println(arr.add(1));
        printArray(arr);
    }

    public static void printArray(Array array) {
        for (int temp : array.getData()) {
            System.out.print(temp + "、");
        }
        System.out.println();
    }
}

/**
 * 数组类
 */
class Array {
    private int[] data; // 数组数据
    private int index;  // 数据增加的索引号

    public Array() {
        this(5);    // 默认设置5个大小
    }

    public Array(int len) { // 动态决定数组大小
        if (len > 0) {
            this.data = new int[len];
        } else {
            this.data = new int[1];
        }
    }

    /** 设置增长容量 */
    public void increment(int cap) {
        int[] newData = new int[this.data.length + cap];    // 开辟新的数组
        System.arraycopy(this.data, 0, newData, 0, this.data.length);   // 数组拷贝
        this.data = newData;    // 修改指向，产生垃圾
    }

    /** 实现数据的增加 */
    public boolean add(int data) {
        if (this.index < this.data.length) {
            this.data[this.index++] = data;
            return true;
        }
        return false;
    }

    public int[] getData() {
        return this.data;
    }
}

/**
 * 数组排序类
 */
class SortArray extends Array {

    public SortArray() {
    }

    public SortArray(int len) {
        super(len);
    }

    @Override
    public int[] getData() {
        java.util.Arrays.sort(super.getData());
        return super.getData();
    }
}

/**
 * 数组反转类
 */
class ReverseArray extends Array {

    public ReverseArray() {
    }

    public ReverseArray(int len) {
        super(len);
    }

    @Override
    public int[] getData() {
        int center = super.getData().length / 2;    // 确定反转次数
        int head = 0;
        int tail = super.getData().length - 1;
        for (int i = 0; i < center; i++) {
            int temp = super.getData()[head];
            super.getData()[head] = super.getData()[tail];
            super.getData()[tail] = temp;
            head++;
            tail--;
        }
        return super.getData();
    }
}
